#!/usr/bin/python
# -*- coding: utf-8 -*-

import datetime

from os.path import abspath, dirname, join

from bottle import Bottle
from bottle import debug, run
from bottle import jinja2_view as view
from bottle import redirect, abort, static_file
from bottle import jinja2_template as template
from bottle import request, response, local

from autumn.db.query import Query

from web_func import get_image_type, check2mkdir

from setting import ENTRY_FILE_PATH, ENTRY_DIR_FUNC

from forms import EntryAddForm
from models import Entry

app = Bottle()

@app.route('/static/<id:int>')
def handle_static(id):
    tmp_dir = ENTRY_DIR_FUNC(id)

    tmp_path = join(tmp_dir, str(id))

    full_path = abspath(join(ENTRY_FILE_PATH, tmp_path))

    return static_file(tmp_path, ENTRY_FILE_PATH, 'image/'+get_image_type(full_path))


@app.route('/add', method=['GET', 'POST'])
def handle_add():
    form = EntryAddForm(obj=request.forms)
    #用not request.files.entry 居然会不行，真他妈奇怪
    if request.method == 'POST' and request.files.entry == '':
        form.entry.errors= [u'请先选择一张图片哦']
        return template('entry/add', form=form)
        
    if request.method == 'POST' and form.validate():
        #read()只能调用一次
        entry_file_data = request.files.entry.file.read()

        if get_image_type(entry_file_data, is_path=False) is None:
            form.entry.errors = [u'图片格式目前仅支持jpg,png,bmp,gif，请您重新选择呗']
            return template('entry/add', form=form)

        obj = Entry(remark=form.remark.data, create_time=datetime.datetime.now())
        obj.save()

        tmp_dir = ENTRY_DIR_FUNC(obj.id)
        full_dir = abspath(join(ENTRY_FILE_PATH, tmp_dir))
        check2mkdir(full_dir)

        full_path = abspath(join(full_dir, str(obj.id)))

        f = file(full_path, 'wb')
        f.write(entry_file_data)
        f.close()

        return redirect('/')

    return template('entry/add', form=form)

@app.route('/list/recent')
def handle_list_recent():
    objlist = Entry.get().order_by('create_time', 'DESC')[:]
    return template('entry/list', datalist=objlist, title_sub_name=u'最近更新')

@app.route('/list/day_top')
def handle_list_day_top():
    now = datetime.datetime.now()
    t = datetime.timedelta(days=1)
    point_day = now - t

    sql = 'select * from entry where create_time>=? order by up_num desc'
    objlist = Query.sql(sql, [point_day])

    return template('entry/list', datalist=objlist, title_sub_name=u'今天最赞')

@app.route('/list/week_top')
def handle_list_week_top():
    now = datetime.datetime.now()
    t = datetime.timedelta(days=7)
    point_day = now - t

    sql = 'select * from entry where create_time>=? order by up_num desc'
    objlist = Query.sql(sql, [point_day])
    return template('entry/list', datalist=objlist, title_sub_name=u'本周最赞')
